package logic

import (
	"context"
	"strconv"
	"strings"

	"mall/service/recommended/api/internal/svc"
	"mall/service/recommended/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetItemNeighborsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetItemNeighborsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetItemNeighborsLogic {
	return &GetItemNeighborsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetItemNeighborsLogic) GetItemNeighbors(
	req *types.ItemSearchReq,
) (resp *types.NeighborsResp, err error) {
	var itemId, userId string
	if len(strings.TrimSpace(req.ItemId)) > 0 && len(strings.TrimSpace(req.ItemId)) > 0 {
		itemId = req.ItemId
		userId = req.UserId
	}
	resp = &types.NeighborsResp{}
	pageSize, err := strconv.ParseInt(req.PageSize, 10, 64)
	if err != nil {
		logx.Errorf("GetItemNeighbors pageSize ParseInt Error: %+v", err)
		return nil, err
	}
	offset, err := strconv.ParseInt(req.Offset, 10, 64)
	if err != nil {
		logx.Errorf("GetItemNeighbors offset ParseInt Error: %+v", err)
		return nil, err
	}
	res, err := l.svcCtx.GorseClient.GetItemNeighbors(l.ctx, itemId, userId, int(pageSize), int(offset))
	if err != nil {
		return resp, err
	}

	for _, v := range res {
		resp.List = append(resp.List, map[string]any{
			"id":    v.Id,
			"score": v.Score,
		})
	}
	return resp, nil
}
